package io.github.wppli.trigger.listener;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import io.github.wppli.domain.pay.event.OrderBehaviorsEvent;
import io.github.wppli.domain.pay.model.entity.ProductEntity;
import io.github.wppli.domain.pay.service.IOrderService;
import io.github.wppli.domain.posts.event.CalculatePostsTfIdfEvent;
import io.github.wppli.domain.posts.model.valobj.UserPostsBehaviorType;
import io.github.wppli.domain.recommond.model.entity.PostsContentEntity;
import io.github.wppli.domain.recommond.model.entity.UserBehaviorEntity;
import io.github.wppli.domain.recommond.repository.IUserBehaviorRepository;
import io.github.wppli.types.event.BaseEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author li--jiaqiang 2025−03−22
 */
@Slf4j
@Component
public class OrderBehaviorsCustomer {


    @Value("${spring.rabbitmq.topic.orderBehaviors}")
    private String topic;

    private final IUserBehaviorRepository userBehaviorRepository;
    private final IOrderService orderService;

    public OrderBehaviorsCustomer(IUserBehaviorRepository repository, IOrderService orderService) {
        this.userBehaviorRepository = repository;
        this.orderService = orderService;
    }

    @RabbitListener(queuesToDeclare = @Queue(value = "${spring.rabbitmq.topic.orderBehaviors}"))
    public void listener(String message) {

        try {
            // 1. 转换对象
            BaseEvent.EventMessage<OrderBehaviorsEvent.OrderBehaviorsEntity> eventMessage =
                    JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<OrderBehaviorsEvent.OrderBehaviorsEntity>>() {
                    }.getType());

            OrderBehaviorsEvent.OrderBehaviorsEntity orderBehaviorsEntity = eventMessage.getData();
            ProductEntity productEntity = orderBehaviorsEntity.getProductEntity();
            UserBehaviorEntity userBehaviorEntity = orderBehaviorsEntity.getUserBehaviorEntity();

            // 保存用户-商品行为
            userBehaviorRepository.save(userBehaviorEntity);
            // 保存商品sku
            orderService.saveProductSku(productEntity);

        } catch (Exception e) {
            log.error("user_product_behaviors_sku 任务，接收MQ消息成功 topic:{} message: {}", topic, message);
            e.printStackTrace();
        }
    }
}